package com.github.wxiaoqi.security.crm.core.biz;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.wxiaoqi.security.auth.common.config.UserAuthConfig;
import com.github.wxiaoqi.security.auth.common.util.SnowFlake;
import com.github.wxiaoqi.security.auth.common.util.jwt.IJWTInfo;
import com.github.wxiaoqi.security.auth.common.util.jwt.JWTHelper;
import com.github.wxiaoqi.security.common.biz.BaseBiz;
import com.github.wxiaoqi.security.common.crm.request.PlatformBaseAddRequest;
import com.github.wxiaoqi.security.common.crm.request.QueryMerchantBaseListRequest;
import com.github.wxiaoqi.security.common.enums.UserTypeEnums;
import com.github.wxiaoqi.security.common.msg.ResponseCode;
import com.github.wxiaoqi.security.common.msg.TableResultResponse;
import com.github.wxiaoqi.security.common.util.EntityUtils;
import com.github.wxiaoqi.security.crm.core.client.FeignAdminClient;
import com.github.wxiaoqi.security.crm.core.entity.PlatformBase;
import com.github.wxiaoqi.security.crm.core.mapper.PlatformBaseMapper;

import lombok.extern.slf4j.Slf4j;
import tk.mybatis.mapper.entity.Example;
import tk.mybatis.mapper.entity.Example.Criteria;

/**
 * 平台基础信息
 *
 * @author centerroot
 * @email ${email}
 * @date 2018-07-16 10:15:48
 */
@Slf4j
@Service
@Transactional(rollbackFor = Exception.class)
public class PlatformBaseBiz extends BaseBiz<PlatformBaseMapper,PlatformBase> {
	
	@Autowired
	private FeignAdminClient feignAdminClient;
    @Autowired
    private UserAuthConfig userAuthConfig;
	/**
	 * 添加
	 */
	public Map<String, Object> addPlatform(PlatformBaseAddRequest res) {
		log.info("添加平台请求参数：{}",EntityUtils.beanToMap(res));
		PlatformBase entity = new PlatformBase();
		BeanUtils.copyProperties(res,entity);
		Map<String, Object> result = new HashMap<String, Object>();
		
		PlatformBase platformBaseReq = new PlatformBase();
		platformBaseReq.setPlatformLoginName(entity.getPlatformLoginName());
		List<PlatformBase> platformBases = mapper.select(platformBaseReq);
		if (platformBases != null && platformBases.size() > 0) {
			result.put("code", ResponseCode.PLATFORM_LOGIN_NAME_EXIST.getCode());
			result.put("msg", ResponseCode.PLATFORM_LOGIN_NAME_EXIST.getMessage());
		}else{
			//添加平台
			long platformId = SnowFlake.getId();
			entity.setPlatformId(String.valueOf(platformId));
			entity.setAuthenticationStatus("00");//第一次添加都是"未认证状态"
			mapper.insert(entity);
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("platformName", entity.getPlatformName());
			map.put("platformLoginName", entity.getPlatformLoginName());
			map.put("platformId", entity.getPlatformId());
			map.put("type", UserTypeEnums.PLATFORM_ADMIN.getCode());
			map.put("token", entity.getToken());
			//this.commonAdd(map);
			Map<String,Object> reMap = feignAdminClient.addPlatformOrMerchant(map);
			String code = (String) reMap.get("code");
			if(ResponseCode.OK.getCode().equals(code)){
				result.put("code", ResponseCode.OK.getCode());
				result.put("msg", ResponseCode.OK.getMessage());
			}else {
				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
				result.put("code", reMap.get("code"));
				result.put("msg", reMap.get("msg"));
			}
		}
		
		return result;
	}
	/**
	 * 添加商户与平台公共方法
	 * 添加平台需传参数 ： platformName，platformId，type为2（int），token
	 * 添加商户需传参数 ： merchantName，merchantId，platformId，type为3（int），token
	 * @param param
	 */
	public void commonAdd2(Map<String, Object> param) {
		String platformName = (String) param.get("platformName");
		String platformLoginName = (String) param.get("platformLoginName");
		String merchantName = (String) param.get("merchantName");
		String platformId = (String) param.get("platformId");
		String merchantId = (String) param.get("merchantId");
		Integer type = (Integer) param.get("type");
		String token = (String) param.get("token");
		String userNo = null;
		String userName = null;
		try {
			IJWTInfo info = JWTHelper.getInfoFromToken(token, userAuthConfig.getPubKeyByte());
			userNo = info.getXId();
			userName = info.getName();
		} catch (Exception e) {
			e.printStackTrace(); 
		}
		
		Map<String, Object> result = new HashMap<String, Object>();
		//dept表添加
		Map<String, Object> deptMap = new HashMap<String, Object>();
		deptMap.put("platformId", Long.valueOf(platformId));
		//如果是平台，平台的父级固定是 海盗集团，id为1，如果修改了最高级目录则要修改修改此处值
		Integer parentId = 1;
		//根据平台编号获取父机构编号
		if(UserTypeEnums.PLATFORM_ADMIN.getCode() != type){
			Map<String, Object> deptPMap = new HashMap<String, Object>();
			deptPMap.put("parentId", 1);
			deptPMap.put("platformId",Long.valueOf(platformId));
			Map<String, Object> deptPResultMap = feignAdminClient.selectByPlatformId(deptPMap);
			String deptPResultCode = (String) deptPResultMap.get("code");
			if(!ResponseCode.OK.getCode().equals(deptPResultCode)){
		    	result.put("code", deptPResultMap.get("code"));
		    	result.put("msg", deptPResultMap.get("msg"));
		    	result.put("success", false);
		    	return;
			}
			Map<String, Object> mapDept = (Map<String, Object>) deptPResultMap.get("dept");
			Integer deptId = (Integer) mapDept.get("id");
			parentId = deptId;
			
		}
		deptMap.put("parentId", parentId);
		if(UserTypeEnums.PLATFORM_ADMIN.getCode() == type){
			deptMap.put("name", platformName);
		}else {
			deptMap.put("name", merchantName);
		}
		
		deptMap.put("delFlag", "0");
		Map<String, Object> deptResultMap = feignAdminClient.addDept(deptMap);
		String deptCode = (String) deptResultMap.get("code");
		if(!ResponseCode.OK.getCode().equals(deptCode)){
	    	result.put("code", deptResultMap.get("code"));
	    	result.put("msg", deptResultMap.get("msg"));
	    	result.put("success", false);
	    	return;
		}
		Integer deptId = (Integer) deptResultMap.get("deptId");
		//添加角色
		Map<String, Object> roleMap = new HashMap<String, Object>();
		if(UserTypeEnums.PLATFORM_ADMIN.getCode() == type){
			roleMap.put("roleName", platformName + "平台管理员");
		}else {
			roleMap.put("roleName", merchantName + "商户管理员");
		}
		
		roleMap.put("remark", "创建平台自动生成角色");
		roleMap.put("deptId", deptId);
		roleMap.put("platformId", platformId);
		roleMap.put("isDelete", 1);
		Map<String, Object> roleResultMap = feignAdminClient.addRole(roleMap);
		Integer roleId = (Integer) roleResultMap.get("roleId");
		//添加用户
		Map<String, Object> userMap = new HashMap<String, Object>();
		userMap.put("userId", SnowFlake.getId());
		userMap.put("crtUser", userNo);
		userMap.put("crtName", userName);
		userMap.put("updUser", userNo);
		userMap.put("updName", userName);
		if(UserTypeEnums.PLATFORM_ADMIN.getCode() == type){
			userMap.put("username", platformLoginName);
		}else {
			userMap.put("username", merchantName);
		}
		//默认密码123456
		userMap.put("password", "123456");
		if(UserTypeEnums.PLATFORM_ADMIN.getCode() == type){
			userMap.put("name", platformName);
		}else {
			userMap.put("name", merchantName);
		}
		userMap.put("deptId", deptId);
		if(UserTypeEnums.PLATFORM_ADMIN.getCode() == type){
			userMap.put("deptName", platformName);
		}else {
			userMap.put("deptName", merchantName);
		}
		userMap.put("description", "添加平台自动添加的平台管理员");
		//userMap.put("crtTime", new Date());
		if(UserTypeEnums.PLATFORM_ADMIN.getCode() != type){
			userMap.put("merchantId", merchantId);
		}
		userMap.put("platformId", platformId);
		if(UserTypeEnums.PLATFORM_ADMIN.getCode() == type){
			userMap.put("userType", UserTypeEnums.PLATFORM_ADMIN.getCode());
		}else {
			userMap.put("userType", UserTypeEnums.MERCHANT_ADMIN.getCode());
		}
		
		Map<String, Object> userResultMap = feignAdminClient.addUser(userMap);
		Long userId = (Long) userResultMap.get("userId");
		//添加关系
		Map<String, Object> userRoleMap = new HashMap<String, Object>();
		userRoleMap.put("userId", userId);
		userRoleMap.put("roleId", roleId);
		Map<String, Object> userRoleResultMap = feignAdminClient.addUserRole(userRoleMap);
		//资源
		Map<String, Object> resourceAuthorityMap = new HashMap<String, Object>();
		resourceAuthorityMap.put("roleId", roleId);
		Map<String, Object> resourceAuthorityResultMap = feignAdminClient.platformAuthority(resourceAuthorityMap);
	}
	
	
	public TableResultResponse<PlatformBase> pageList(QueryMerchantBaseListRequest bean){
		log.info("查询平台列表请求参数：{}",EntityUtils.beanToMap(bean));
		Example example = new Example(PlatformBase.class);
		TableResultResponse tableResultResponse = null;
		if (bean.getPage() <= 0) {
			PlatformBase platformBase = new PlatformBase();
			platformBase.setPlatformLevel("02");
			List<PlatformBase> list = mapper.select(platformBase);
			tableResultResponse = new TableResultResponse<PlatformBase>(list.size(), list);
		} else {
			Criteria criteria = example.createCriteria();
			example.setOrderByClause("create_time desc");
			Page<PlatformBase> result = PageHelper.startPage(bean.getPage(), bean.getLimit());
			List<PlatformBase> list = mapper.selectByExample(example);
			tableResultResponse = new TableResultResponse<PlatformBase>(result.getTotal(), list);
		}
		return tableResultResponse;
	}
	
	/**
	 * 根据平台编号查询平台信息
	 * @author centerroot
	 * @time 创建时间:2018年8月16日上午10:15:57
	 * @param platformId
	 * @return
	 */
	public Map<String, Object> getOneObj(String platformId){
		log.info("【根据平台编号查询平台信息】   请求参数：platformId:{}",platformId);
		Map<String, Object> respMap = new HashMap<String, Object>();
		PlatformBase platformBaseReq = new PlatformBase();
		platformBaseReq.setPlatformId(platformId);
        List<PlatformBase> list = mapper.select(platformBaseReq);
		if (list != null && list.size() > 0) {
			PlatformBase platformBase = list.get(0);
			if (platformBase.getPlatformLogo() != null) {
				platformBase.setPlatformLogoStr(new String(platformBase.getPlatformLogo()));
			}
			respMap.put("platformBase", platformBase);
			respMap.put("code", ResponseCode.OK.getCode());
	        respMap.put("msg", ResponseCode.OK.getMessage());
		} else {
			respMap.put("code", ResponseCode.ABNORMAL_FIELDS.getCode());
	        respMap.put("msg", ResponseCode.ABNORMAL_FIELDS.getMessage());
		}
		
		log.info("【根据平台编号查询平台信息】   响应参数：{}",respMap);
		return respMap;
	}
	
	/**
	 * 根据序号删除平台
	 * @author centerroot
	 * @time 创建时间:2018年8月24日下午2:50:55
	 * @param id
	 * @return
	 */
	public Map<String, Object> deleteOne(Integer id){
		log.info("【根据序号删除平台信息】   请求参数：id:{}",id);
		Map<String, Object> respMap = new HashMap<String, Object>();
		PlatformBase platformBase = mapper.selectByPrimaryKey(id);
		
		Map<String, Object> reqMap = new HashMap<String, Object>();
		reqMap.put("platformId", platformBase.getPlatformId());
		reqMap.put("platformName", platformBase.getPlatformName());
		reqMap.put("type", 2);
		respMap = feignAdminClient.deletePlatformOrMerchant(reqMap);
		mapper.deleteByPrimaryKey(id);
		
		log.info("【根据序号删除平台信息】   响应参数：{}",respMap);
		return respMap;
	}
	
	public Map<String, Object> updateObj(PlatformBaseAddRequest entity){
		log.info("【修改平台信息】   请求参数：{}",EntityUtils.beanToMap(entity));
		Map<String, Object> respMap = new HashMap<String, Object>();
		
		PlatformBase platformBase = new PlatformBase();
		BeanUtils.copyProperties(entity,platformBase);
		EntityUtils.setUpdatedInfo(platformBase);
	    mapper.updateByPrimaryKeySelective(platformBase);
	    Map<String,Object> reqMap = new HashMap<>();
	    reqMap.put("platformId", platformBase.getPlatformId());
	    reqMap.put("platformName", platformBase.getPlatformName());
	    respMap = feignAdminClient.updateDept(reqMap);
		
		log.info("【修改平台信息】   响应参数：{}",respMap);
		return respMap;
	}
	
}